<?php

include "db.php";

/* =========================================================
   BASIC SETTINGS
========================================================= */

date_default_timezone_set('Asia/Kabul');


/* =========================================================
   FILTER PARAMETERS
========================================================= */

$type_filter = $_GET['type'] ?? 'all';

$customer_id = $_GET['customer_id'] ?? '';
$supplier_id = $_GET['supplier_id'] ?? '';

$product_id = $_GET['product_id'] ?? '';
$unit_id = $_GET['unit_id'] ?? '';

$filter_day = $_GET['day'] ?? '';
$filter_month = $_GET['month'] ?? '';
$filter_year = $_GET['year'] ?? '';

$filter_today = isset($_GET['today']) ? date('Y-m-d') : '';

$filter_from_date = $_GET['from_date'] ?? '';
$filter_to_date = $_GET['to_date'] ?? '';


/* =========================================================
   SAFE INTEGER VALUES
========================================================= */

$customer_id_int = null;
$supplier_id_int = null;
$product_id_int = null;
$unit_id_int = null;

if ($customer_id !== '' && is_numeric($customer_id)) {
    $customer_id_int = intval($customer_id);
}

if ($supplier_id !== '' && is_numeric($supplier_id)) {
    $supplier_id_int = intval($supplier_id);
}

if ($product_id !== '' && is_numeric($product_id)) {
    $product_id_int = intval($product_id);
}

if ($unit_id !== '' && is_numeric($unit_id)) {
    $unit_id_int = intval($unit_id);
}


/* =========================================================
   BASE WHERE
========================================================= */

$where_sales = "WHERE 1";
$where_sales_returns = "WHERE 1";
$where_purchases = "WHERE 1";
$where_purchase_returns = "WHERE 1";
$where_expenses = "WHERE 1";
$where_repayments = "WHERE 1";


/* =========================================================
   FETCH CUSTOMER LIST
========================================================= */

$customer_list = [];

$result = $conn->query("
    SELECT
        customer_id AS id,
        name
    FROM customers
    ORDER BY name ASC
");

if ($result) {

    while ($row = $result->fetch_assoc()) {

        $customer_list[] = $row;

    }

}


/* =========================================================
   FETCH SUPPLIER LIST
========================================================= */

$supplier_list = [];

$result = $conn->query("
    SELECT
        supplier_id AS id,
        name
    FROM suppliers
    ORDER BY name ASC
");

if ($result) {

    while ($row = $result->fetch_assoc()) {

        $supplier_list[] = $row;

    }

}


/* =========================================================
   FETCH UNIT LIST
========================================================= */

$unit_list = [];

$result = $conn->query("
    SELECT
        unit_id,
        unit_name
    FROM units
    ORDER BY unit_name ASC
");

if ($result) {

    while ($row = $result->fetch_assoc()) {

        $unit_list[] = $row;

    }

}


/* =========================================================
   FETCH PRODUCT LIST
========================================================= */

$product_list = [];

$result = $conn->query("
    SELECT
        p.product_id,
        p.name,
        p.barcode,
        p.unit_id,
        u.unit_name
    FROM products p
    LEFT JOIN units u
        ON u.unit_id = p.unit_id
    ORDER BY p.name ASC
");

if ($result) {

    while ($row = $result->fetch_assoc()) {

        $product_list[] = $row;

    }

}


/* =========================================================
   CUSTOMER FILTER
========================================================= */

if ($customer_id_int !== null) {

    if ($customer_id_int === 0) {

        $where_sales .= "
            AND (
                sales.customer_id IS NULL
                OR sales.customer_id = 0
            )
        ";

        $where_sales_returns .= "
            AND (
                returns.customer_id IS NULL
                OR returns.customer_id = 0
            )
        ";

        $where_repayments .= "
            AND repayments.customer_id IS NULL
        ";

    } else {

        $where_sales .= "
            AND sales.customer_id = $customer_id_int
        ";

        $where_sales_returns .= "
            AND returns.customer_id = $customer_id_int
        ";

        $where_repayments .= "
            AND repayments.customer_id = $customer_id_int
        ";

    }

}


/* =========================================================
   SUPPLIER FILTER
========================================================= */

if ($supplier_id_int !== null) {

    $where_purchases .= "
        AND purchases.supplier_id = $supplier_id_int
    ";

    $where_purchase_returns .= "
        AND purchase_returns.supplier_id = $supplier_id_int
    ";

    $where_repayments .= "
        AND repayments.supplier_id = $supplier_id_int
    ";

}


/* =========================================================
   PRODUCT / UNIT FILTER
========================================================= */

/* -------------------------
   SALES
------------------------- */

if ($product_id_int !== null || $unit_id_int !== null) {

    $where_sales .= "
        AND EXISTS (
            SELECT 1
            FROM sale_items si_filter
            INNER JOIN products p_filter
                ON p_filter.product_id = si_filter.product_id
            WHERE si_filter.sale_id = sales.sale_id
    ";

    if ($product_id_int !== null) {

        $where_sales .= "
            AND p_filter.product_id = $product_id_int
        ";

    }

    if ($unit_id_int !== null) {

        $where_sales .= "
            AND p_filter.unit_id = $unit_id_int
        ";

    }

    $where_sales .= "
        )
    ";

}


/* -------------------------
   SALES RETURNS
------------------------- */

if ($product_id_int !== null || $unit_id_int !== null) {

    $where_sales_returns .= "
        AND EXISTS (
            SELECT 1
            FROM return_items ri_filter
            INNER JOIN products p_filter
                ON p_filter.product_id = ri_filter.product_id
            WHERE ri_filter.return_id = returns.return_id
    ";

    if ($product_id_int !== null) {

        $where_sales_returns .= "
            AND p_filter.product_id = $product_id_int
        ";

    }

    if ($unit_id_int !== null) {

        $where_sales_returns .= "
            AND p_filter.unit_id = $unit_id_int
        ";

    }

    $where_sales_returns .= "
        )
    ";

}


/* -------------------------
   PURCHASES
------------------------- */

if ($product_id_int !== null || $unit_id_int !== null) {

    $where_purchases .= "
        AND EXISTS (
            SELECT 1
            FROM purchase_items pi_filter
            INNER JOIN products p_filter
                ON p_filter.product_id = pi_filter.product_id
            WHERE pi_filter.purchase_id = purchases.purchase_id
    ";

    if ($product_id_int !== null) {

        $where_purchases .= "
            AND p_filter.product_id = $product_id_int
        ";

    }

    if ($unit_id_int !== null) {

        $where_purchases .= "
            AND p_filter.unit_id = $unit_id_int
        ";

    }

    $where_purchases .= "
        )
    ";

}


/* -------------------------
   PURCHASE RETURNS
------------------------- */

if ($product_id_int !== null || $unit_id_int !== null) {

    $where_purchase_returns .= "
        AND EXISTS (
            SELECT 1
            FROM purchase_return_items pri_filter
            INNER JOIN products p_filter
                ON p_filter.product_id = pri_filter.product_id
            WHERE pri_filter.purchase_return_id =
                  purchase_returns.purchase_return_id
    ";

    if ($product_id_int !== null) {

        $where_purchase_returns .= "
            AND p_filter.product_id = $product_id_int
        ";

    }

    if ($unit_id_int !== null) {

        $where_purchase_returns .= "
            AND p_filter.unit_id = $unit_id_int
        ";

    }

    $where_purchase_returns .= "
        )
    ";

}


/* =========================================================
   DATE FILTER FUNCTION
========================================================= */

function applyDateFilter(
    $where,
    $day,
    $month,
    $year,
    $today,
    $from,
    $to,
    $field
) {

    if ($today) {

        $where .= "
            AND DATE($field) = '" . addslashes($today) . "'
        ";

    } elseif ($from && $to) {

        $where .= "
            AND DATE($field)
            BETWEEN '" . addslashes($from) . "'
            AND '" . addslashes($to) . "'
        ";

    } else {

        if ($day) {

            $where .= "
                AND DAY($field) = " . intval($day);

        }

        if ($month) {

            $where .= "
                AND MONTH($field) = " . intval($month);

        }

        if ($year) {

            $where .= "
                AND YEAR($field) = " . intval($year);

        }

    }

    return $where;

}


/* =========================================================
   APPLY DATE FILTERS
========================================================= */

$where_sales = applyDateFilter(
    $where_sales,
    $filter_day,
    $filter_month,
    $filter_year,
    $filter_today,
    $filter_from_date,
    $filter_to_date,
    'sales.sale_date'
);

$where_sales_returns = applyDateFilter(
    $where_sales_returns,
    $filter_day,
    $filter_month,
    $filter_year,
    $filter_today,
    $filter_from_date,
    $filter_to_date,
    'returns.return_date'
);

$where_purchases = applyDateFilter(
    $where_purchases,
    $filter_day,
    $filter_month,
    $filter_year,
    $filter_today,
    $filter_from_date,
    $filter_to_date,
    'purchases.purchase_date'
);

$where_purchase_returns = applyDateFilter(
    $where_purchase_returns,
    $filter_day,
    $filter_month,
    $filter_year,
    $filter_today,
    $filter_from_date,
    $filter_to_date,
    'purchase_returns.return_date'
);

$where_expenses = applyDateFilter(
    $where_expenses,
    $filter_day,
    $filter_month,
    $filter_year,
    $filter_today,
    $filter_from_date,
    $filter_to_date,
    'expenses.expense_date'
);

$where_repayments = applyDateFilter(
    $where_repayments,
    $filter_day,
    $filter_month,
    $filter_year,
    $filter_today,
    $filter_from_date,
    $filter_to_date,
    'repayments.created_at'
);


/* =========================================================
   TOTAL SALES
========================================================= */

$result = $conn->query("
    SELECT
        COALESCE(SUM(total),0) AS t
    FROM sales
    $where_sales
");

$sales_total = $result
    ? (float)$result->fetch_assoc()['t']
    : 0;


/* =========================================================
   SALES RETURNS
========================================================= */

$result = $conn->query("
    SELECT
        COALESCE(SUM(total_refund),0) AS t
    FROM returns
    $where_sales_returns
");

$sales_return = $result
    ? (float)$result->fetch_assoc()['t']
    : 0;


/* =========================================================
   TOTAL PURCHASES
========================================================= */

$result = $conn->query("
    SELECT
        COALESCE(SUM(total),0) AS t
    FROM purchases
    $where_purchases
");

$purchase_total = $result
    ? (float)$result->fetch_assoc()['t']
    : 0;


/* =========================================================
   PURCHASE RETURNS
========================================================= */

$result = $conn->query("
    SELECT
        COALESCE(SUM(total_refund),0) AS t
    FROM purchase_returns
    $where_purchase_returns
");

$purchase_return = $result
    ? (float)$result->fetch_assoc()['t']
    : 0;


/* =========================================================
   EXPENSES
========================================================= */

$result = $conn->query("
    SELECT
        COALESCE(SUM(amount),0) AS t
    FROM expenses
    $where_expenses
");

$expenses = $result
    ? (float)$result->fetch_assoc()['t']
    : 0;


/* =========================================================
   CUSTOMER REPAYMENTS
========================================================= */

$result = $conn->query("
    SELECT
        COALESCE(SUM(amount),0) AS t
    FROM repayments
    $where_repayments
    AND type = 'customer'
");

$total_repayment_from_customers = $result
    ? (float)$result->fetch_assoc()['t']
    : 0;


/* =========================================================
   SUPPLIER REPAYMENTS
========================================================= */

$result = $conn->query("
    SELECT
        COALESCE(SUM(amount),0) AS t
    FROM repayments
    $where_repayments
    AND type = 'supplier'
");

$total_repayment_to_suppliers = $result
    ? (float)$result->fetch_assoc()['t']
    : 0;


/* =========================================================
   CUSTOMER CURRENT BALANCE
========================================================= */

$customer_balance_sql = "
    SELECT
        COALESCE(
            SUM(

                COALESCE(c.opening_balance,0)

                +

                COALESCE(
                    (
                        SELECT
                            SUM(
                                COALESCE(s.total,0)
                                -
                                COALESCE(s.payment,0)
                            )
                        FROM sales s
                        WHERE s.customer_id = c.customer_id
";


if ($product_id_int !== null || $unit_id_int !== null) {

    $customer_balance_sql .= "
        AND EXISTS (
            SELECT 1
            FROM sale_items si_cb
            INNER JOIN products p_cb
                ON p_cb.product_id = si_cb.product_id
            WHERE si_cb.sale_id = s.sale_id
    ";

    if ($product_id_int !== null) {

        $customer_balance_sql .= "
            AND p_cb.product_id = $product_id_int
        ";

    }

    if ($unit_id_int !== null) {

        $customer_balance_sql .= "
            AND p_cb.unit_id = $unit_id_int
        ";

    }

    $customer_balance_sql .= "
        )
    ";

}


$customer_balance_sql .= "

                    ),
                    0
                )

                -

                COALESCE(
                    (
                        SELECT
                            SUM(COALESCE(r.total_refund,0))
                        FROM returns r
                        WHERE r.customer_id = c.customer_id
";


if ($product_id_int !== null || $unit_id_int !== null) {

    $customer_balance_sql .= "
        AND EXISTS (
            SELECT 1
            FROM return_items ri_cb
            INNER JOIN products p_cb
                ON p_cb.product_id = ri_cb.product_id
            WHERE ri_cb.return_id = r.return_id
    ";

    if ($product_id_int !== null) {

        $customer_balance_sql .= "
            AND p_cb.product_id = $product_id_int
        ";

    }

    if ($unit_id_int !== null) {

        $customer_balance_sql .= "
            AND p_cb.unit_id = $unit_id_int
        ";

    }

    $customer_balance_sql .= "
        )
    ";

}


$customer_balance_sql .= "

                    ),
                    0
                )

                -

                COALESCE(
                    (
                        SELECT
                            SUM(COALESCE(rp.amount,0))
                        FROM repayments rp
                        WHERE rp.customer_id = c.customer_id
                        AND rp.type = 'customer'
                    ),
                    0
                )

            ),
            0
        ) AS balance

    FROM customers c
    WHERE 1
";


if ($customer_id_int !== null) {

    if ($customer_id_int === 0) {

        $customer_balance_sql .= "
            AND 1 = 0
        ";

    } else {

        $customer_balance_sql .= "
            AND c.customer_id = $customer_id_int
        ";

    }

}


$result = $conn->query($customer_balance_sql);

$customer_balance = $result
    ? (float)$result->fetch_assoc()['balance']
    : 0;


/* =========================================================
   SUPPLIER CURRENT BALANCE
========================================================= */

$supplier_balance_sql = "
    SELECT
        COALESCE(
            SUM(

                COALESCE(s.opening_balance,0)

                +

                COALESCE(
                    (
                        SELECT
                            SUM(COALESCE(p.total,0))
                        FROM purchases p
                        WHERE p.supplier_id = s.supplier_id
";


if ($product_id_int !== null || $unit_id_int !== null) {

    $supplier_balance_sql .= "
        AND EXISTS (
            SELECT 1
            FROM purchase_items pi_sb
            INNER JOIN products p_sb
                ON p_sb.product_id = pi_sb.product_id
            WHERE pi_sb.purchase_id = p.purchase_id
    ";

    if ($product_id_int !== null) {

        $supplier_balance_sql .= "
            AND p_sb.product_id = $product_id_int
        ";

    }

    if ($unit_id_int !== null) {

        $supplier_balance_sql .= "
            AND p_sb.unit_id = $unit_id_int
        ";

    }

    $supplier_balance_sql .= "
        )
    ";

}


$supplier_balance_sql .= "

                    ),
                    0
                )

                -

                COALESCE(
                    (
                        SELECT
                            SUM(COALESCE(pr.total_refund,0))
                        FROM purchase_returns pr
                        WHERE pr.supplier_id = s.supplier_id
";


if ($product_id_int !== null || $unit_id_int !== null) {

    $supplier_balance_sql .= "
        AND EXISTS (
            SELECT 1
            FROM purchase_return_items pri_sb
            INNER JOIN products p_sb
                ON p_sb.product_id = pri_sb.product_id
            WHERE pri_sb.purchase_return_id =
                  pr.purchase_return_id
    ";

    if ($product_id_int !== null) {

        $supplier_balance_sql .= "
            AND p_sb.product_id = $product_id_int
        ";

    }

    if ($unit_id_int !== null) {

        $supplier_balance_sql .= "
            AND p_sb.unit_id = $unit_id_int
        ";

    }

    $supplier_balance_sql .= "
        )
    ";

}


$supplier_balance_sql .= "

                    ),
                    0
                )

                -

                COALESCE(
                    (
                        SELECT
                            SUM(COALESCE(rp.amount,0))
                        FROM repayments rp
                        WHERE rp.supplier_id = s.supplier_id
                        AND rp.type = 'supplier'
                    ),
                    0
                )

            ),
            0
        ) AS balance

    FROM suppliers s
    WHERE 1
";


if ($supplier_id_int !== null) {

    $supplier_balance_sql .= "
        AND s.supplier_id = $supplier_id_int
    ";

}


$result = $conn->query($supplier_balance_sql);

$supplier_balance = $result
    ? (float)$result->fetch_assoc()['balance']
    : 0;


/* =========================================================
   CURRENT STOCK VALUE
========================================================= */

$stock_value_sql = "
    SELECT
        COALESCE(
            SUM(
                COALESCE(stock,0) *
                COALESCE(purchase_price,0)
            ),
            0
        ) AS total_stock_value
    FROM products
    WHERE 1
";


if ($product_id_int !== null) {

    $stock_value_sql .= "
        AND product_id = $product_id_int
    ";

}


if ($unit_id_int !== null) {

    $stock_value_sql .= "
        AND unit_id = $unit_id_int
    ";

}


$result = $conn->query($stock_value_sql);

$stock_value = $result
    ? (float)$result->fetch_assoc()['total_stock_value']
    : 0;


/* =========================================================
   PAID SALES AMOUNT
========================================================= */

$paid_sales_sql = "
    SELECT
        COALESCE(SUM(COALESCE(payment,0)),0) AS total_paid
    FROM sales
    $where_sales
";

$result = $conn->query($paid_sales_sql);

$total_paid_sales = $result
    ? (float)$result->fetch_assoc()['total_paid']
    : 0;


/* =========================================================
   NET BALANCE
========================================================= */

$net_balance =
      $customer_balance
    + $total_paid_sales
    + $stock_value
    - $supplier_balance
    - $expenses;


/* =========================================================
   ITEM PROFIT
========================================================= */

$profit_sql = "
    SELECT
        COALESCE(
            SUM(
                (si.price - p.purchase_price) * si.qty
            ),
            0
        ) AS t

    FROM sale_items si

    INNER JOIN sales s
        ON s.sale_id = si.sale_id

    INNER JOIN products p
        ON p.product_id = si.product_id

    WHERE 1
";


if ($customer_id_int !== null) {

    if ($customer_id_int === 0) {

        $profit_sql .= "
            AND (
                s.customer_id IS NULL
                OR s.customer_id = 0
            )
        ";

    } else {

        $profit_sql .= "
            AND s.customer_id = $customer_id_int
        ";

    }

}


if ($product_id_int !== null) {

    $profit_sql .= "
        AND p.product_id = $product_id_int
    ";

}


if ($unit_id_int !== null) {

    $profit_sql .= "
        AND p.unit_id = $unit_id_int
    ";

}


$profit_sql = applyDateFilter(
    $profit_sql,
    $filter_day,
    $filter_month,
    $filter_year,
    $filter_today,
    $filter_from_date,
    $filter_to_date,
    's.sale_date'
);


$result = $conn->query($profit_sql);

$total_item_profit = $result
    ? (float)$result->fetch_assoc()['t']
    : 0;


/* =========================================================
   RETURN PROFIT
========================================================= */

$return_profit_sql = "
    SELECT
        COALESCE(
            SUM(
                (ri.refund_amount - p.purchase_price) * ri.qty
            ),
            0
        ) AS t

    FROM return_items ri

    INNER JOIN returns r
        ON r.return_id = ri.return_id

    INNER JOIN products p
        ON p.product_id = ri.product_id

    WHERE 1
";


if ($customer_id_int !== null) {

    if ($customer_id_int === 0) {

        $return_profit_sql .= "
            AND (
                r.customer_id IS NULL
                OR r.customer_id = 0
            )
        ";

    } else {

        $return_profit_sql .= "
            AND r.customer_id = $customer_id_int
        ";

    }

}


if ($product_id_int !== null) {

    $return_profit_sql .= "
        AND p.product_id = $product_id_int
    ";

}


if ($unit_id_int !== null) {

    $return_profit_sql .= "
        AND p.unit_id = $unit_id_int
    ";

}


$return_profit_sql = applyDateFilter(
    $return_profit_sql,
    $filter_day,
    $filter_month,
    $filter_year,
    $filter_today,
    $filter_from_date,
    $filter_to_date,
    'r.return_date'
);


$result = $conn->query($return_profit_sql);

$total_return_profit = $result
    ? (float)$result->fetch_assoc()['t']
    : 0;


/* =========================================================
   NET ITEM PROFIT AFTER RETURNS
========================================================= */

$net_item_profit_after_returns =
    $total_item_profit - $total_return_profit;


/* =========================================================
   NET INCOME
========================================================= */

$net_income =
      $sales_total
    - $purchase_total
    - $sales_return
    + $purchase_return
    + $total_repayment_from_customers
    - $total_repayment_to_suppliers
    - $expenses;


/* =========================================================
   COUNTS
========================================================= */

$result = $conn->query("
    SELECT COUNT(*) AS c
    FROM customers
");

$total_customers = $result
    ? (int)$result->fetch_assoc()['c']
    : 0;


$result = $conn->query("
    SELECT COUNT(*) AS c
    FROM suppliers
");

$total_suppliers = $result
    ? (int)$result->fetch_assoc()['c']
    : 0;


/* =========================================================
   TODAY CASH INCOME
========================================================= */

$result = $conn->query("
    SELECT
        COALESCE(SUM(payment),0) AS t
    FROM sales
    WHERE DATE(sale_date) = CURDATE()
");

$today_cash_income = $result
    ? (float)$result->fetch_assoc()['t']
    : 0;


/* =========================================================
   TODAY PROFIT
========================================================= */

$today_profit_sql = "
    SELECT
        COALESCE(
            SUM(
                (si.price - p.purchase_price) * si.qty
            ),
            0
        ) AS t

    FROM sale_items si

    INNER JOIN sales s
        ON s.sale_id = si.sale_id

    INNER JOIN products p
        ON p.product_id = si.product_id

    WHERE DATE(s.sale_date) = CURDATE()
";


if ($customer_id_int !== null) {

    if ($customer_id_int === 0) {

        $today_profit_sql .= "
            AND (
                s.customer_id IS NULL
                OR s.customer_id = 0
            )
        ";

    } else {

        $today_profit_sql .= "
            AND s.customer_id = $customer_id_int
        ";

    }

}


if ($product_id_int !== null) {

    $today_profit_sql .= "
        AND p.product_id = $product_id_int
    ";

}


if ($unit_id_int !== null) {

    $today_profit_sql .= "
        AND p.unit_id = $unit_id_int
    ";

}


$result = $conn->query($today_profit_sql);

$today_profit = $result
    ? (float)$result->fetch_assoc()['t']
    : 0;


/* =========================================================
   TODAY RETURN PROFIT
========================================================= */

$today_return_profit_sql = "
    SELECT
        COALESCE(
            SUM(
                (ri.refund_amount - p.purchase_price) * ri.qty
            ),
            0
        ) AS t

    FROM return_items ri

    INNER JOIN returns r
        ON r.return_id = ri.return_id

    INNER JOIN products p
        ON p.product_id = ri.product_id

    WHERE DATE(r.return_date) = CURDATE()
";


if ($customer_id_int !== null) {

    if ($customer_id_int === 0) {

        $today_return_profit_sql .= "
            AND (
                r.customer_id IS NULL
                OR r.customer_id = 0
            )
        ";

    } else {

        $today_return_profit_sql .= "
            AND r.customer_id = $customer_id_int
        ";

    }

}


if ($product_id_int !== null) {

    $today_return_profit_sql .= "
        AND p.product_id = $product_id_int
    ";

}


if ($unit_id_int !== null) {

    $today_return_profit_sql .= "
        AND p.unit_id = $unit_id_int
    ";

}


$result = $conn->query($today_return_profit_sql);

$today_return_profit = $result
    ? (float)$result->fetch_assoc()['t']
    : 0;


$today_profit -= $today_return_profit;


/* =========================================================
   =========================================================
   TODAY SUMMARY - SAME CARDS
   =========================================================
========================================================= */


/* =========================================================
   TODAY WHERE CLAUSES
========================================================= */

$today_where_sales =
    "WHERE DATE(sales.sale_date) = CURDATE()";

$today_where_sales_returns =
    "WHERE DATE(returns.return_date) = CURDATE()";

$today_where_purchases =
    "WHERE DATE(purchases.purchase_date) = CURDATE()";

$today_where_purchase_returns =
    "WHERE DATE(purchase_returns.return_date) = CURDATE()";

$today_where_expenses =
    "WHERE DATE(expenses.expense_date) = CURDATE()";

$today_where_repayments =
    "WHERE DATE(repayments.created_at) = CURDATE()";


/* =========================================================
   TODAY CUSTOMER FILTER
========================================================= */

if ($customer_id_int !== null) {

    if ($customer_id_int === 0) {

        $today_where_sales .= "
            AND (
                sales.customer_id IS NULL
                OR sales.customer_id = 0
            )
        ";

        $today_where_sales_returns .= "
            AND (
                returns.customer_id IS NULL
                OR returns.customer_id = 0
            )
        ";

    } else {

        $today_where_sales .= "
            AND sales.customer_id = $customer_id_int
        ";

        $today_where_sales_returns .= "
            AND returns.customer_id = $customer_id_int
        ";

    }

}


/* =========================================================
   TODAY SUPPLIER FILTER
========================================================= */

if ($supplier_id_int !== null) {

    $today_where_purchases .= "
        AND purchases.supplier_id = $supplier_id_int
    ";

    $today_where_purchase_returns .= "
        AND purchase_returns.supplier_id = $supplier_id_int
    ";

}


/* =========================================================
   TODAY PRODUCT / UNIT FILTER
========================================================= */

if ($product_id_int !== null || $unit_id_int !== null) {


    /* -------------------------
       TODAY SALES
    ------------------------- */

    $today_where_sales .= "
        AND EXISTS (
            SELECT 1
            FROM sale_items si_today
            INNER JOIN products p_today
                ON p_today.product_id = si_today.product_id
            WHERE si_today.sale_id = sales.sale_id
    ";

    if ($product_id_int !== null) {

        $today_where_sales .= "
            AND p_today.product_id = $product_id_int
        ";

    }

    if ($unit_id_int !== null) {

        $today_where_sales .= "
            AND p_today.unit_id = $unit_id_int
        ";

    }

    $today_where_sales .= "
        )
    ";


    /* -------------------------
       TODAY SALES RETURNS
    ------------------------- */

    $today_where_sales_returns .= "
        AND EXISTS (
            SELECT 1
            FROM return_items ri_today
            INNER JOIN products p_today
                ON p_today.product_id = ri_today.product_id
            WHERE ri_today.return_id = returns.return_id
    ";

    if ($product_id_int !== null) {

        $today_where_sales_returns .= "
            AND p_today.product_id = $product_id_int
        ";

    }

    if ($unit_id_int !== null) {

        $today_where_sales_returns .= "
            AND p_today.unit_id = $unit_id_int
        ";

    }

    $today_where_sales_returns .= "
        )
    ";


    /* -------------------------
       TODAY PURCHASES
    ------------------------- */

    $today_where_purchases .= "
        AND EXISTS (
            SELECT 1
            FROM purchase_items pi_today
            INNER JOIN products p_today
                ON p_today.product_id = pi_today.product_id
            WHERE pi_today.purchase_id = purchases.purchase_id
    ";

    if ($product_id_int !== null) {

        $today_where_purchases .= "
            AND p_today.product_id = $product_id_int
        ";

    }

    if ($unit_id_int !== null) {

        $today_where_purchases .= "
            AND p_today.unit_id = $unit_id_int
        ";

    }

    $today_where_purchases .= "
        )
    ";


    /* -------------------------
       TODAY PURCHASE RETURNS
    ------------------------- */

    $today_where_purchase_returns .= "
        AND EXISTS (
            SELECT 1
            FROM purchase_return_items pri_today
            INNER JOIN products p_today
                ON p_today.product_id = pri_today.product_id
            WHERE pri_today.purchase_return_id =
                  purchase_returns.purchase_return_id
    ";

    if ($product_id_int !== null) {

        $today_where_purchase_returns .= "
            AND p_today.product_id = $product_id_int
        ";

    }

    if ($unit_id_int !== null) {

        $today_where_purchase_returns .= "
            AND p_today.unit_id = $unit_id_int
        ";

    }

    $today_where_purchase_returns .= "
        )
    ";

}


/* =========================================================
   TODAY SALES
========================================================= */

$result = $conn->query("
    SELECT
        COALESCE(SUM(total),0) AS t
    FROM sales
    $today_where_sales
");

$today_sales_total = $result
    ? (float)$result->fetch_assoc()['t']
    : 0;


/* =========================================================
   TODAY SALES RETURNS
========================================================= */

$result = $conn->query("
    SELECT
        COALESCE(SUM(total_refund),0) AS t
    FROM returns
    $today_where_sales_returns
");

$today_sales_return = $result
    ? (float)$result->fetch_assoc()['t']
    : 0;


/* =========================================================
   TODAY PURCHASES
========================================================= */

$result = $conn->query("
    SELECT
        COALESCE(SUM(total),0) AS t
    FROM purchases
    $today_where_purchases
");

$today_purchase_total = $result
    ? (float)$result->fetch_assoc()['t']
    : 0;


/* =========================================================
   TODAY PURCHASE RETURNS
========================================================= */

$result = $conn->query("
    SELECT
        COALESCE(SUM(total_refund),0) AS t
    FROM purchase_returns
    $today_where_purchase_returns
");

$today_purchase_return = $result
    ? (float)$result->fetch_assoc()['t']
    : 0;


/* =========================================================
   TODAY EXPENSES
========================================================= */

$result = $conn->query("
    SELECT
        COALESCE(SUM(amount),0) AS t
    FROM expenses
    $today_where_expenses
");

$today_expenses = $result
    ? (float)$result->fetch_assoc()['t']
    : 0;


/* =========================================================
   TODAY CUSTOMER REPAYMENTS
========================================================= */

$today_customer_repayment_where =
    "WHERE DATE(repayments.created_at) = CURDATE()";

if ($customer_id_int !== null && $customer_id_int > 0) {

    $today_customer_repayment_where .= "
        AND repayments.customer_id = $customer_id_int
    ";

}

$result = $conn->query("
    SELECT
        COALESCE(SUM(amount),0) AS t
    FROM repayments
    $today_customer_repayment_where
    AND type = 'customer'
");

$today_repayment_from_customers = $result
    ? (float)$result->fetch_assoc()['t']
    : 0;


/* =========================================================
   TODAY SUPPLIER REPAYMENTS
========================================================= */

$today_supplier_repayment_where =
    "WHERE DATE(repayments.created_at) = CURDATE()";

if ($supplier_id_int !== null) {

    $today_supplier_repayment_where .= "
        AND repayments.supplier_id = $supplier_id_int
    ";

}

$result = $conn->query("
    SELECT
        COALESCE(SUM(amount),0) AS t
    FROM repayments
    $today_supplier_repayment_where
    AND type = 'supplier'
");

$today_repayment_to_suppliers = $result
    ? (float)$result->fetch_assoc()['t']
    : 0;


/* =========================================================
   TODAY PAID SALES
   هغه پیسې چې د خرڅلاو پر وخت واقعاً اخیستل شوې دي
========================================================= */

$result = $conn->query("
    SELECT
        COALESCE(
            SUM(COALESCE(payment,0)),
            0
        ) AS t
    FROM sales
    $today_where_sales
");

$today_paid_sales = $result
    ? (float)$result->fetch_assoc()['t']
    : 0;


/* =========================================================
   TODAY QARZ / CREDIT SALES
   ټول خرڅلاو - د خرڅلاو پر وخت اخیستل شوې پیسې
========================================================= */

$result = $conn->query("
    SELECT
        COALESCE(
            SUM(
                GREATEST(
                    COALESCE(total,0) - COALESCE(payment,0),
                    0
                )
            ),
            0
        ) AS t
    FROM sales
    $today_where_sales
");

$today_qarz = $result
    ? (float)$result->fetch_assoc()['t']
    : 0;


/* =========================================================
   TODAY NET INCOME
========================================================= */

$today_net_income =
      $today_sales_total
    - $today_purchase_total
    - $today_sales_return
    + $today_purchase_return
    + $today_repayment_from_customers
    - $today_repayment_to_suppliers
    - $today_expenses;


/* =========================================================
   TODAY CUSTOMER DEBT
========================================================= */

$today_customer_debt =
      $today_sales_total
    - $today_paid_sales
    - $today_sales_return;

if ($today_customer_debt < 0) {
    $today_customer_debt = 0;
}


/* =========================================================
   TODAY SUPPLIER DEBT
========================================================= */

$today_supplier_debt =
      $today_purchase_total
    - $today_purchase_return
    - $today_repayment_to_suppliers;

if ($today_supplier_debt < 0) {
    $today_supplier_debt = 0;
}


/* =========================================================
   TODAY NET BALANCE
========================================================= */

$today_net_balance =
      $today_customer_debt
    + $today_paid_sales
    + $stock_value
    - $today_supplier_debt
    - $today_expenses;

/* =========================================================
   TODAY ITEM PROFIT
========================================================= */

$today_item_profit_sql = "
    SELECT
        COALESCE(
            SUM(
                (si.price - p.purchase_price) * si.qty
            ),
            0
        ) AS t

    FROM sale_items si

    INNER JOIN sales s
        ON s.sale_id = si.sale_id

    INNER JOIN products p
        ON p.product_id = si.product_id

    WHERE DATE(s.sale_date) = CURDATE()
";


if ($customer_id_int !== null) {

    if ($customer_id_int === 0) {

        $today_item_profit_sql .= "
            AND (
                s.customer_id IS NULL
                OR s.customer_id = 0
            )
        ";

    } else {

        $today_item_profit_sql .= "
            AND s.customer_id = $customer_id_int
        ";

    }

}


if ($product_id_int !== null) {

    $today_item_profit_sql .= "
        AND p.product_id = $product_id_int
    ";

}


if ($unit_id_int !== null) {

    $today_item_profit_sql .= "
        AND p.unit_id = $unit_id_int
    ";

}


$result = $conn->query($today_item_profit_sql);

$today_item_profit = $result
    ? (float)$result->fetch_assoc()['t']
    : 0;


/* =========================================================
   TODAY RETURN PROFIT
========================================================= */

$today_return_profit_sql = "
    SELECT
        COALESCE(
            SUM(
                (ri.refund_amount - p.purchase_price) * ri.qty
            ),
            0
        ) AS t

    FROM return_items ri

    INNER JOIN returns r
        ON r.return_id = ri.return_id

    INNER JOIN products p
        ON p.product_id = ri.product_id

    WHERE DATE(r.return_date) = CURDATE()
";


if ($customer_id_int !== null) {

    if ($customer_id_int === 0) {

        $today_return_profit_sql .= "
            AND (
                r.customer_id IS NULL
                OR r.customer_id = 0
            )
        ";

    } else {

        $today_return_profit_sql .= "
            AND r.customer_id = $customer_id_int
        ";

    }

}


if ($product_id_int !== null) {

    $today_return_profit_sql .= "
        AND p.product_id = $product_id_int
    ";

}


if ($unit_id_int !== null) {

    $today_return_profit_sql .= "
        AND p.unit_id = $unit_id_int
    ";

}


$result = $conn->query($today_return_profit_sql);

$today_return_profit = $result
    ? (float)$result->fetch_assoc()['t']
    : 0;


$today_net_item_profit =
    $today_item_profit - $today_return_profit;


/* =========================================================
   SAFE DISPLAY HELPER
========================================================= */

function safe_html($value)
{
    return htmlspecialchars(
        (string)($value ?? ''),
        ENT_QUOTES,
        'UTF-8'
    );
}


/* =========================================================
   CURRENT FILTER QUERY
========================================================= */

$print_query = $_GET;


/* =========================================================
   CURRENT FILTER CARDS
========================================================= */

$cards = [

    [
        'title' => 'قرض  ',
        'value' => $customer_balance,
        'icon'  => 'fa-user-tie',
        'bg'    => '#0d6efd,#6610f2',
        'class' => ''
    ],

    [
        'title' => 'پر دوکان قرض د شرکتونو ',
        'value' => $supplier_balance,
        'icon'  => 'fa-truck-loading',
        'bg'    => '#dc3545,#fd7e14',
        'class' => ''
    ],

    [
        'title' => '  سټاک  ',
        'value' => $stock_value,
        'icon'  => 'fa-boxes',
        'bg'    => '#198754,#20c997',
        'class' => 'stock-card'
    ],

    [
        'title' => ' ټوله سرمایه',
        'value' => $net_balance,
        'icon'  => 'fa-wallet',
        'bg'    => '#6f42c1,#d63384',
        'class' => 'net-balance-card'
    ],

    [
        'title' => 'د نن ورځی دخل',
        'value' => $today_cash_income,
        'icon'  => 'fa-cash-register',
        'bg'    => '#198754,#20c997',
        'class' => ''
    ],

    [
        'title' => 'د نن ورځی ګټه',
        'value' => $today_profit,
        'icon'  => 'fa-coins',
        'bg'    => '#f39c12,#e67e22',
        'class' => ''
    ],

    [
        'title' => 'ټول خرڅلاو',
        'value' => $sales_total,
        'icon'  => 'fa-money-bill-wave',
        'bg'    => '#6610f2,#6f42c1',
        'class' => ''
    ],

    [
        'title' => 'ټول خرید',
        'value' => $purchase_total,
        'icon'  => 'fa-shopping-cart',
        'bg'    => '#198754,#28a745',
        'class' => ''
    ],

    [
     'title' => 'د خرڅلاو واپسي',
        'value' => $sales_return,
        'icon'  => 'fa-undo-alt',
        'bg'    => '#dc3545,#fd7e14',
        'class' => ''
    ],

    [
       'title' => 'د خرید واپسي',
        'value' => $purchase_return,
        'icon'  => 'fa-undo',
        'bg'    => '#ffc107,#fd7e14',
        'class' => ''
    ],

    [
        'title' => 'د مشتریانو څخه تادیه',
        'value' => $total_repayment_from_customers,
        'icon'  => 'fa-money-check-alt',
        'bg'    => '#20c997,#0dcaf0',
        'class' => ''
    ],

    [
        'title' => ' عرضه کوونکو ته تادیه',
        'value' => $total_repayment_to_suppliers,
        'icon'  => 'fa-hand-holding',
        'bg'    => '#fd7e14,#ffc107',
        'class' => ''
    ],

  

    [
        'title' => 'د توکو خالص ګټه',
        'value' => $net_item_profit_after_returns,
        'icon'  => 'fa-coins',
        'bg'    => '#2ecc71,#27ae60',
        'class' => ''
    ],

    [
        'title' => 'ټول مشتریان',
        'value' => $total_customers,
        'icon'  => 'fa-users',
        'bg'    => '#198754,#28a745',
        'class' => ''
    ],

    [
        'title' => 'ټول عرضه کوونکي',
        'value' => $total_suppliers,
        'icon'  => 'fa-truck',
        'bg'    => '#0dcaf0,#0d6efd',
        'class' => ''
    ],

    [
     'title' => 'خرچ',
        'value' => $expenses,
        'icon'  => 'fa-money-bill-wave',
        'bg'    => '#dc3545,#fd7e14',
        'class' => ''
    ]

];


/* =========================================================
   TODAY CARDS
========================================================= */

$today_cards = [

    [
        'title' => 'د نن ورځې قرض',
        'value' => $today_customer_debt,
        'icon'  => 'fa-user-tie',
        'bg'    => '#0d6efd,#6610f2',
        'class' => ''
    ],
    
    [
        'title' => 'پر دوکان قرض د شرکتونو',
        'value' => $today_supplier_debt,
        'icon'  => 'fa-truck-loading',
        'bg'    => '#dc3545,#fd7e14',
        'class' => ''
    ],

    [
        'title' => ' سټاک  ',
        'value' => $stock_value,
        'icon'  => 'fa-boxes',
        'bg'    => '#198754,#20c997',
        'class' => 'stock-card'
    ],

    [
        'title' => ' سرمایه',
        'value' => $today_net_balance,
        'icon'  => 'fa-wallet',
        'bg'    => '#6f42c1,#d63384',
        'class' => 'net-balance-card'
    ],
    [
        'title' => 'د نن ورځې دخل',
        'value' => $today_paid_sales,
        'icon'  => 'fa-cash-register',
        'bg'    => '#198754,#20c997',
        'class' => ''
    ],
    
    [
        'title' => 'د نن ورځې قرض',
        'value' => $today_qarz,
        'icon'  => 'fa-hand-holding-usd',
        'bg'    => '#dc3545,#fd7e14',
        'class' => ''
    ],

    [
        'title' => 'د نن ورځی ګټه',
        'value' => $today_net_item_profit,
        'icon'  => 'fa-coins',
        'bg'    => '#f39c12,#e67e22',
        'class' => ''
    ],

    [
        'title' => 'ټول خرڅلاو',
        'value' => $today_sales_total,
        'icon'  => 'fa-money-bill-wave',
        'bg'    => '#6610f2,#6f42c1',
        'class' => ''
    ],

    [
        'title' => 'ټول خرید',
        'value' => $today_purchase_total,
        'icon'  => 'fa-shopping-cart',
        'bg'    => '#198754,#28a745',
        'class' => ''
    ],

    [
        'title' => 'د خرڅلاو واپسي',
        'value' => $today_sales_return,
        'icon'  => 'fa-undo-alt',
        'bg'    => '#dc3545,#fd7e14',
        'class' => ''
    ],

    [
        'title' => 'د خرید واپسي',
        'value' => $today_purchase_return,
        'icon'  => 'fa-undo',
        'bg'    => '#ffc107,#fd7e14',
        'class' => ''
    ],

    [
        'title' => 'د مشتریانو څخه تادیه',
        'value' => $today_repayment_from_customers,
        'icon'  => 'fa-money-check-alt',
        'bg'    => '#20c997,#0dcaf0',
        'class' => ''
    ],

    [
        'title' => ' عرضه کوونکو ته تادیه',
        'value' => $today_repayment_to_suppliers,
        'icon'  => 'fa-hand-holding',
        'bg'    => '#fd7e14,#ffc107',
        'class' => ''
    ],

 

    [
        'title' => 'د توکو خالص ګټه',
        'value' => $today_net_item_profit,
        'icon'  => 'fa-coins',
        'bg'    => '#2ecc71,#27ae60',
        'class' => ''
    ],

    [
        'title' => 'ټول مشتریان',
        'value' => $total_customers,
        'icon'  => 'fa-users',
        'bg'    => '#198754,#28a745',
        'class' => ''
    ],

    [
        'title' => 'ټول عرضه کوونکي',
        'value' => $total_suppliers,
        'icon'  => 'fa-truck',
        'bg'    => '#0dcaf0,#0d6efd',
        'class' => ''
    ],

    [
        'title' => 'خرچ',
        'value' => $today_expenses,
        'icon'  => 'fa-money-bill-wave',
        'bg'    => '#dc3545,#fd7e14',
        'class' => ''
    ]

];

?>

<!DOCTYPE html>

<html lang="ps" dir="rtl">

<head>

<meta charset="UTF-8">

<meta name="viewport"
      content="width=device-width, initial-scale=1.0">

<title>POS راپور</title>

<link href="assets/css/bootstrap.rtl.min.css"
      rel="stylesheet">

<link href="assets/css/all.min.css"
      rel="stylesheet">


<style>

/* =========================================================
   GENERAL
========================================================= */

body {

    background:
        linear-gradient(
            135deg,
            #f5f7fa 0%,
            #eef2f7 100%
        );

    font-family: Tahoma, sans-serif;

    min-height: 100vh;
}

h2 {

    margin-top: 20px;
    margin-bottom: 20px;

    font-weight: 800;

    text-align: center;

    color: #263238;
}


/* =========================================================
   FILTER
========================================================= */

.filter-form {

    margin-bottom: 0;
}

.filter-form label {

    font-weight: bold;

    margin-bottom: 5px;

    color: #343a40;
}

.filter-form .form-select,
.filter-form .form-control {

    min-height: 42px;

    border-radius: 10px;

    border: 1px solid #dce1e7;
}

.filter-form .form-select:focus,
.filter-form .form-control:focus {

    border-color: #6f42c1;

    box-shadow:
        0 0 0 .2rem rgba(111,66,193,.12);
}


/* =========================================================
   FILTER BOX
========================================================= */

.filter-box {

    background: #fff;

    border-radius: 20px;

    padding: 22px;

    box-shadow:
        0 5px 20px rgba(0,0,0,.06);

    margin-bottom: 25px;

    border: 1px solid rgba(0,0,0,.04);
}

.filter-title {

    font-size: 19px;

    font-weight: 800;

    margin-bottom: 18px;

    color: #343a40;

    display: flex;

    align-items: center;

    gap: 8px;
}


/* =========================================================
   BUTTONS
========================================================= */

.btn {

    border-radius: 11px;

    font-weight: 700;

    min-height: 42px;
}

.btn-back {

    margin-bottom: 20px;

    border-radius: 12px;

    padding: 10px 18px;
}


/* =========================================================
   ACTIVE FILTER
========================================================= */

.active-filter {

    border-radius: 15px;

    font-size: 15px;

    border: none;

    box-shadow:
        0 4px 12px rgba(13,110,253,.08);
}


/* =========================================================
   FINANCIAL TITLE
========================================================= */

.financial-title {

    font-weight: 800;

    font-size: 23px;

    margin-top: 10px;

    margin-bottom: 18px;

    padding-bottom: 12px;

    border-bottom:
        2px solid #dee2e6;

    color: #263238;

    display: flex;

    align-items: center;

    gap: 10px;
}


/* =========================================================
   TODAY SUMMARY TITLE
========================================================= */

.today-summary-title {

    font-weight: 800;

    font-size: 23px;

    margin-top: 10px;

    margin-bottom: 18px;

    padding-bottom: 12px;

    border-bottom:
        2px solid #dee2e6;

    color: #263238;

    display: flex;

    align-items: center;

    gap: 10px;
}

.today-date-badge {

    margin-right: auto;

    background:
        linear-gradient(
            135deg,
            #198754,
            #20c997
        );

    color: #fff;

    padding: 8px 15px;

    border-radius: 12px;

    font-size: 14px;

    font-weight: 700;
}


/* =========================================================
   REPORT TABS
========================================================= */

.report-tabs {

    background: #fff;

    padding: 8px;

    border-radius: 18px;

    box-shadow:
        0 5px 20px rgba(0,0,0,.06);

    margin-bottom: 25px;

    border: 1px solid rgba(0,0,0,.04);
}

.report-tabs .nav-link {

    border: 0;

    border-radius: 13px;

    padding: 13px 25px;

    font-weight: 800;

    color: #495057;

    transition: .25s ease;
}

.report-tabs .nav-link:hover {

    background: #f1f3f5;

    color: #0d6efd;
}

.report-tabs .nav-link.active {

    color: #fff;

    background:
        linear-gradient(
            135deg,
            #0d6efd,
            #6610f2
        );

    box-shadow:
        0 5px 15px rgba(13,110,253,.25);
}


/* =========================================================
   SUMMARY CARD COLUMN
========================================================= */

.summary-card-col {

    display: flex;
}


/* =========================================================
   MODERN SUMMARY CARDS
========================================================= */

.card {

    width: 100%;

    height: 205px;

    min-height: 205px;

    border: 0;

    border-radius: 22px;

    color: #fff;

    text-align: center;

    position: relative;

    overflow: hidden;

    display: flex;

    flex-direction: column;

    align-items: center;

    justify-content: center;

    padding: 20px !important;

    box-shadow:
        0 8px 20px rgba(0,0,0,.10),
        inset 0 1px 0 rgba(255,255,255,.18);

    transition:
        transform .25s ease,
        box-shadow .25s ease;
}


/* =========================================================
   DECORATIVE CIRCLES
========================================================= */

.card::before {

    content: "";

    position: absolute;

    width: 120px;

    height: 120px;

    top: -45px;

    left: -35px;

    border-radius: 50%;

    background:
        rgba(255,255,255,.10);
}

.card::after {

    content: "";

    position: absolute;

    width: 90px;

    height: 90px;

    bottom: -35px;

    right: -25px;

    border-radius: 50%;

    background:
        rgba(255,255,255,.08);
}


/* =========================================================
   CARD HOVER
========================================================= */

.card:hover {

    transform:
        translateY(-7px);

    box-shadow:
        0 15px 30px rgba(0,0,0,.16),
        inset 0 1px 0 rgba(255,255,255,.25);
}


/* =========================================================
   CARD ICON
========================================================= */

.card-icon {

    position: relative;

    z-index: 2;

    width: 62px;

    height: 62px;

    display: flex;

    align-items: center;

    justify-content: center;

    margin-bottom: 12px;

    border-radius: 18px;

    font-size: 27px;

    background:
        rgba(255,255,255,.18);

    border:
        1px solid rgba(255,255,255,.25);

    box-shadow:
        0 5px 15px rgba(0,0,0,.10);

    backdrop-filter: blur(5px);
}


/* =========================================================
   CARD TITLE
========================================================= */

.card h5 {

    position: relative;

    z-index: 2;

    font-size: 16px;

    font-weight: 700;

    margin:
        0 0 8px 0;

    line-height: 1.4;

    white-space: nowrap;
}


/* =========================================================
   CARD VALUE
========================================================= */

.card h3 {

    position: relative;

    z-index: 2;

    font-size: 24px;

    font-weight: 800;

    margin: 0;

    line-height: 1.2;

    direction: ltr;

    letter-spacing: .3px;

    text-shadow:
        0 2px 4px rgba(0,0,0,.15);
}


/* =========================================================
   SPECIAL CARDS
========================================================= */

.net-balance-card {

    border:
        2px solid rgba(255,255,255,.55);

    box-shadow:
        0 12px 30px rgba(111,66,193,.30),
        inset 0 1px 0 rgba(255,255,255,.25);
}

.stock-card {

    border:
        2px solid rgba(255,255,255,.35);

    box-shadow:
        0 10px 25px rgba(25,135,84,.22),
        inset 0 1px 0 rgba(255,255,255,.20);
}


/* =========================================================
   ROW ALIGNMENT
========================================================= */

.row.g-4 {

    align-items: stretch;
}


/* =========================================================
   FOOTER
========================================================= */

footer {

    text-align: center;

    padding: 20px;

    margin-top: 45px;

    font-size: 14px;

    color: #6c757d;
}


/* =========================================================
   MOBILE
========================================================= */

@media (max-width: 768px) {

    .card {

        height: 185px;

        min-height: 185px;

        border-radius: 19px;

        padding: 15px !important;
    }

    .card-icon {

        width: 54px;

        height: 54px;

        border-radius: 15px;

        font-size: 23px;

        margin-bottom: 9px;
    }

    .card h5 {

        font-size: 14px;

        margin-bottom: 7px;
    }

    .card h3 {

        font-size: 20px;
    }

    .today-summary-title {

        font-size: 18px;

        flex-wrap: wrap;
    }

    .today-date-badge {

        margin-right: 0;

        width: 100%;

        text-align: center;

        margin-top: 8px;
    }

}


@media (max-width: 576px) {

    .card {

        height: 175px;

        min-height: 175px;
    }

    .card h5 {

        font-size: 13px;
    }

    .card h3 {

        font-size: 19px;
    }

    .report-tabs .nav-link {

        padding: 11px 8px;

        font-size: 13px;
    }

}

</style>

</head>


<body>


<div class="container mt-4">


<!-- =====================================================
     TITLE
===================================================== -->

<h2>

    <i class="fas fa-chart-pie"></i>

    POS راپور

</h2>


<!-- =====================================================
     BACK BUTTON
===================================================== -->

<a href="index.php"
   class="btn btn-secondary btn-back">

    <i class="fas fa-home"></i>

    بیرته ډشبورډ ته

</a>


<!-- =====================================================
     FILTER FORM
===================================================== -->

<div class="filter-box">

<div class="filter-title">

    <i class="fas fa-filter"></i>

    د راپور فلټر

</div>


<form method="get"
      class="row g-3 filter-form">


<!-- TYPE -->

<div class="col-md-2">

<label>
    ډول
</label>

<select name="type"
        class="form-select">

<option value="all"
    <?= $type_filter == 'all' ? 'selected' : '' ?>>

    ټول

</option>

<option value="customer"
    <?= $type_filter == 'customer' ? 'selected' : '' ?>>

    مشتری

</option>

<option value="supplier"
    <?= $type_filter == 'supplier' ? 'selected' : '' ?>>

    عرضه کوونکی

</option>

</select>

</div>


<!-- CUSTOMER -->

<div class="col-md-2">

<label>
    مشتری
</label>

<select name="customer_id"
        class="form-select">

<option value="">
    ټول مشتریان
</option>

<option value="0"
    <?= ($customer_id === '0') ? 'selected' : '' ?>>

    Walk-in مشتری

</option>


<?php foreach ($customer_list as $c): ?>

<option
    value="<?= safe_html($c['id']) ?>"
    <?= ($customer_id == $c['id']) ? 'selected' : '' ?>>

    <?= safe_html($c['name']) ?>

</option>

<?php endforeach; ?>

</select>

</div>


<!-- SUPPLIER -->

<div class="col-md-2">

<label>
    عرضه کوونکی
</label>

<select name="supplier_id"
        class="form-select">

<option value="">
    ټول عرضه کوونکي
</option>


<?php foreach ($supplier_list as $s): ?>

<option
    value="<?= safe_html($s['id']) ?>"
    <?= ($supplier_id == $s['id']) ? 'selected' : '' ?>>

    <?= safe_html($s['name']) ?>

</option>

<?php endforeach; ?>

</select>

</div>


<!-- PRODUCT -->

<div class="col-md-3">

<label>
    محصول
</label>

<select name="product_id"
        class="form-select">

<option value="">
    ټول محصولات
</option>


<?php foreach ($product_list as $p): ?>

<option
    value="<?= safe_html($p['product_id']) ?>"
    <?= ($product_id == $p['product_id']) ? 'selected' : '' ?>>

    <?= safe_html($p['name']) ?>

    <?php if (!empty($p['barcode'])): ?>

        - <?= safe_html($p['barcode']) ?>

    <?php endif; ?>

</option>

<?php endforeach; ?>

</select>

</div>


<!-- UNIT -->

<div class="col-md-2">

<label>
    واحد
</label>

<select name="unit_id"
        class="form-select">

<option value="">
    ټول واحدونه
</option>


<?php foreach ($unit_list as $u): ?>

<option
    value="<?= safe_html($u['unit_id']) ?>"
    <?= ($unit_id == $u['unit_id']) ? 'selected' : '' ?>>

    <?= safe_html($u['unit_name']) ?>

</option>

<?php endforeach; ?>

</select>

</div>


<!-- DAY -->

<div class="col-md-1">

<label>
    ورځ
</label>

<select name="day"
        class="form-select">

<option value="">
    ټول
</option>

<?php for ($d = 1; $d <= 31; $d++): ?>

<option
    value="<?= $d ?>"
    <?= ($filter_day == $d) ? 'selected' : '' ?>>

    <?= $d ?>

</option>

<?php endfor; ?>

</select>

</div>


<!-- MONTH -->

<div class="col-md-1">

<label>
    میاشت
</label>

<select name="month"
        class="form-select">

<option value="">
    ټول
</option>

<?php for ($m = 1; $m <= 12; $m++): ?>

<option
    value="<?= $m ?>"
    <?= ($filter_month == $m) ? 'selected' : '' ?>>

    <?= $m ?>

</option>

<?php endfor; ?>

</select>

</div>


<!-- YEAR -->

<div class="col-md-1">

<label>
    کال
</label>

<select name="year"
        class="form-select">

<option value="">
    ټول
</option>

<?php for ($y = date('Y'); $y >= 2020; $y--): ?>

<option
    value="<?= $y ?>"
    <?= ($filter_year == $y) ? 'selected' : '' ?>>

    <?= $y ?>

</option>

<?php endfor; ?>

</select>

</div>


<!-- FROM DATE -->

<div class="col-md-2">

<label>
    له نېټې څخه
</label>

<input
    type="date"
    name="from_date"
    class="form-control"
    value="<?= safe_html($filter_from_date) ?>">

</div>


<!-- TO DATE -->

<div class="col-md-2">

<label>
    تر نېټې پورې
</label>

<input
    type="date"
    name="to_date"
    class="form-control"
    value="<?= safe_html($filter_to_date) ?>">

</div>


<!-- TODAY -->

<div class="col-md-1 d-flex align-items-end">

<div class="form-check">

<input
    class="form-check-input"
    type="checkbox"
    name="today"
    id="todayCheck"
    <?= $filter_today ? 'checked' : '' ?>>

<label
    class="form-check-label"
    for="todayCheck">

    نن

</label>

</div>

</div>


<!-- FILTER -->

<div class="col-md-2 d-flex align-items-end">

<button
    type="submit"
    class="btn btn-primary w-100">

    <i class="fas fa-filter"></i>

    فلټر کول

</button>

</div>


<!-- RESET -->

<div class="col-md-2 d-flex align-items-end">

<a
    href="?"
    class="btn btn-warning w-100">

    <i class="fas fa-redo"></i>

    ریست

</a>

</div>


<!-- PRINT -->

<div class="col-md-2 d-flex align-items-end">

<a
    href="report_print.php?<?= safe_html(http_build_query($print_query)) ?>"
    target="_blank"
    class="btn btn-success w-100">

    <i class="fas fa-print"></i>

    چاپ راپور

</a>

</div>


</form>

</div>


<!-- =====================================================
     ACTIVE FILTER DISPLAY
===================================================== -->

<?php if (
    $customer_id !== '' ||
    $supplier_id !== '' ||
    $product_id !== '' ||
    $unit_id !== '' ||
    $filter_day !== '' ||
    $filter_month !== '' ||
    $filter_year !== '' ||
    $filter_today ||
    ($filter_from_date && $filter_to_date)
): ?>

<div class="alert alert-info active-filter">

<strong>

    <i class="fas fa-filter"></i>

    فعال فلټرونه:

</strong>


<?php if ($customer_id !== ''): ?>

<span class="badge bg-primary">
    مشتری
</span>

<?php endif; ?>


<?php if ($supplier_id !== ''): ?>

<span class="badge bg-danger">
    عرضه کوونکی
</span>

<?php endif; ?>


<?php if ($product_id !== ''): ?>

<span class="badge bg-success">
    محصول
</span>

<?php endif; ?>


<?php if ($unit_id !== ''): ?>

<span class="badge bg-info">
    واحد
</span>

<?php endif; ?>


<?php if ($filter_day !== ''): ?>

<span class="badge bg-secondary">
    ورځ: <?= safe_html($filter_day) ?>
</span>

<?php endif; ?>


<?php if ($filter_month !== ''): ?>

<span class="badge bg-secondary">
    میاشت: <?= safe_html($filter_month) ?>
</span>

<?php endif; ?>


<?php if ($filter_year !== ''): ?>

<span class="badge bg-secondary">
    کال: <?= safe_html($filter_year) ?>
</span>

<?php endif; ?>


<?php if ($filter_today): ?>

<span class="badge bg-dark">
    نن
</span>

<?php endif; ?>


<?php if ($filter_from_date && $filter_to_date): ?>

<span class="badge bg-dark">

    <?= safe_html($filter_from_date) ?>

    →

    <?= safe_html($filter_to_date) ?>

</span>

<?php endif; ?>


</div>

<?php endif; ?>


<!-- =====================================================
     REPORT TABS
===================================================== -->

<div class="report-tabs">

<ul class="nav nav-pills nav-fill"
    id="reportTabs"
    role="tablist">


<li class="nav-item"
    role="presentation">

<button
    class="nav-link active"
    id="filtered-tab"
    data-bs-toggle="pill"
    data-bs-target="#filtered-report"
    type="button"
    role="tab">

    <i class="fas fa-chart-pie"></i>

    مالي وضعیت

</button>

</li>


<li class="nav-item"
    role="presentation">

<button
    class="nav-link"
    id="today-tab"
    data-bs-toggle="pill"
    data-bs-target="#today-report"
    type="button"
    role="tab">

    <i class="fas fa-calendar-day"></i>

    د نن ورځې لنډیز

</button>

</li>


</ul>

</div>


<!-- =====================================================
     TAB CONTENT
===================================================== -->

<div class="tab-content"
     id="reportTabsContent">


<!-- =====================================================
     FIRST TAB
===================================================== -->

<div
    class="tab-pane fade show active"
    id="filtered-report"
    role="tabpanel"
    aria-labelledby="filtered-tab">


<div class="financial-title">

    <i class="fas fa-chart-pie"></i>

    مالي وضعیت

</div>


<div class="row g-4">


<?php foreach ($cards as $c): ?>

<div class="col-12 col-sm-6 col-md-4 col-lg-3 summary-card-col">

<div
    class="card shadow-sm <?= safe_html($c['class']) ?>"
    style="
        background:
        linear-gradient(
            135deg,
            <?= safe_html($c['bg']) ?>
        )
    ">


<i class="fas <?= safe_html($c['icon']) ?> card-icon"></i>


<h5>

    <?= safe_html($c['title']) ?>

</h5>


<h3>

<?php

if (is_numeric($c['value'])) {

    echo number_format(
        (float)$c['value'],
        2
    );

} else {

    echo safe_html($c['value']);

}

?>

</h3>


</div>

</div>

<?php endforeach; ?>


</div>

</div>


<!-- =====================================================
     SECOND TAB - TODAY SUMMARY
===================================================== -->

<div
    class="tab-pane fade"
    id="today-report"
    role="tabpanel"
    aria-labelledby="today-tab">


<div class="today-summary-title">

    <i class="fas fa-calendar-day"></i>

    د نن ورځې مالي لنډیز

    <span class="today-date-badge">

        <i class="fas fa-calendar"></i>

        <?= date('Y-m-d') ?>

    </span>

</div>


<div
    class="alert alert-success"
    style="
        border-radius:15px;
        font-weight:700;
    ">

    <i class="fas fa-info-circle"></i>

    د نن ورځې
    <?= date('Y-m-d') ?>
    ټول مهم مالي معلومات په لاندې کارتونو کې ښودل شوي دي.

</div>


<div class="row g-4">


<?php foreach ($today_cards as $c): ?>

<div class="col-12 col-sm-6 col-md-4 col-lg-3 summary-card-col">

<div
    class="card shadow-sm <?= safe_html($c['class']) ?>"
    style="
        background:
        linear-gradient(
            135deg,
            <?= safe_html($c['bg']) ?>
        )
    ">


<i class="fas <?= safe_html($c['icon']) ?> card-icon"></i>


<h5>

    <?= safe_html($c['title']) ?>

</h5>


<h3>

<?php

if (is_numeric($c['value'])) {

    echo number_format(
        (float)$c['value'],
        2
    );

} else {

    echo safe_html($c['value']);

}

?>

</h3>


</div>

</div>

<?php endforeach; ?>


</div>

</div>


</div>


</div>


<!-- =====================================================
     FOOTER
===================================================== -->

<footer>

    POS سیستم | ورژن 1.0.0 | © <?= date('Y') ?>

</footer>


<script src="assets/js/bootstrap.bundle.min.js"></script>


</body>

</html>